package com.example.myspring.servlet;


import com.example.myspring.entity.Student;
import com.example.myspring.util.ExcelServletUtil;
import com.example.myspring.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

@WebServlet(name = "ExcelForMysqlServlet", value = "/ExcelForMysqlServlet")
@MultipartConfig
//该类用于将前端传入的excel表格批量生成对象传入数据库
public class ExcelForMysqlServlet extends HttpServlet {

    @Autowired
    private StudentService service;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建对象集合
        ArrayList<Student> Students = new ArrayList<Student>();

        //拿到数据
        Part filePart = req.getPart("excelFile");
        //获取输入流
        InputStream input = filePart.getInputStream();

        //对象获取完毕
        Students = ExcelServletUtil.excelForStudent(input, Students);

        //循环调用add函数 将每个Student对象作为参数依次传递
        for (Student stu : Students) {
//            System.out.println(stu);
            service.addStudent(stu);
        }

        req.setAttribute("Students", Students);//写入请求头域
        req.getRequestDispatcher("index.jsp").forward(req, resp);//转发至展示界面
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
